package com.qikecn.api.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jfinal.json.Json;
import com.qikecn.utils.NullUtil;
import com.qikecn.utils.SpyMemcachedUtil;

import java.io.Serializable;
import java.util.List;

/**
 * 内存数据库缓存   用于后台管理
 * @author wangst
 */
public class MemcachedManagerUser implements Serializable{

	/**
	 * 
	 */

	
	private static final int expire = 3600 * 48;
	private static final long serialVersionUID = 1115797622058558754L;

	/**
	 * 保存用户信息到内存数据库
	 * @param key
	 * @param user
	 * @return
	 */
	public static boolean setMemcachedUser(String key, Tuser user, List<Trole> roles,List<Tresource> resources){
		boolean flag = false;
		if(SpyMemcachedUtil.keyExists("key_"+user.getStr("id"))){//禁止同时登录
			String keyTemp = SpyMemcachedUtil.get("key_"+user.getStr("id")).toString();
			deleteMemcachedUser(keyTemp);
		}
		//保存登录信息
		MemcachedManagerUser memcachedUser = new MemcachedManagerUser();
		memcachedUser.setKey(key);
		memcachedUser.setUser(user);
		memcachedUser.setRoles(roles);
		memcachedUser.setResources(resources);
		SpyMemcachedUtil.set("key_"+user.getStr("id"), key, expire);
		SpyMemcachedUtil.set(key+"_id", JSON.toJSONString(memcachedUser), expire);
		return flag;
	}

	/**
	 * 从内容数据库获取用户信息
	 * @param key
	 * @return
	 */
	public static MemcachedManagerUser getMemcachedUser(String key){
		MemcachedManagerUser memcachedUser = null;
		if(SpyMemcachedUtil.keyExists(key+"_id")){
			memcachedUser = JSON.parseObject((String)SpyMemcachedUtil.get(key + "_id"),new TypeReference<MemcachedManagerUser>(){});
		}
		return memcachedUser;
	}
	
	/**
	 * 清除内存数据库信息
	 * @param key
	 */
	public static void deleteMemcachedUser(String key){
		if(SpyMemcachedUtil.keyExists(key+"_id")){
			SpyMemcachedUtil.delete( NullUtil.ifNull(SpyMemcachedUtil.get("key_"+ SpyMemcachedUtil.get(key + "_id")) ) );
			SpyMemcachedUtil.delete( NullUtil.ifNull(SpyMemcachedUtil.get(key + "_id")));
		}
	}
	private String key;
	private Tuser user;
	private List<Trole> roles;
	private List<Tresource> resources;

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public Tuser getUser() {
		return user;
	}

	public void setUser(Tuser user) {
		this.user = user;
	}

	public List<Trole> getRoles() {
		return roles;
	}

	public void setRoles(List<Trole> roles) {
		this.roles = roles;
	}

	public List<Tresource> getResources() {
		return resources;
	}

	public void setResources(List<Tresource> resources) {
		this.resources = resources;
	}
}
